<script setup lang="ts">
import { reactive, ref } from 'vue';
import { NButton, NPopconfirm, NSpace, NTag } from 'naive-ui';
import { fetchFillDataList, deleteFillData, submitFillData } from '@/service/api';
import { useBoolean, useLoading } from '@/hooks/common';
import { $t } from '@/locales';
import DataOperateDrawer from './modules/data-operate-drawer.vue';
import DataApprovalModal from './modules/data-approval-modal.vue';

const { loading, startLoading, endLoading } = useLoading(false);
const { bool: visible, setTrue: openDrawer, setFalse: closeDrawer } = useBoolean();
const { bool: approvalVisible, setTrue: openApproval, setFalse: closeApproval } = useBoolean();

const queryParams = reactive<Api.Dataplatform.FillDataSearchParams>({
  pageNum: 1,
  pageSize: 10,
  templateId: undefined,
  submitStatus: undefined,
  approvalStatus: undefined,
  submitBy: undefined,
  projectId: undefined
});

const tableData = ref<Api.Dataplatform.FillData[]>([]);
const total = ref(0);
const operateType = ref<'add' | 'edit'>('add');
const editingData = ref<Api.Dataplatform.FillData | null>(null);
const approvingData = ref<Api.Dataplatform.FillData | null>(null);

const submitStatusOptions = [
  { label: $t('page.dataplatform.fill.statusDraft'), value: 'DRAFT' },
  { label: $t('page.dataplatform.fill.statusSubmitted'), value: 'SUBMITTED' },
  { label: $t('page.dataplatform.fill.statusApproved'), value: 'APPROVED' },
  { label: $t('page.dataplatform.fill.statusRejected'), value: 'REJECTED' }
];

const columns = [
  { key: 'id', title: 'ID', width: 80 },
  { key: 'templateName', title: $t('page.dataplatform.fill.templateName'), width: 150 },
  {
    key: 'submitStatus',
    title: $t('page.dataplatform.fill.submitStatus'),
    width: 120,
    render: (row: Api.Dataplatform.FillData) => {
      const tagTypes: Record<string, 'default' | 'info' | 'success' | 'error'> = {
        DRAFT: 'default',
        SUBMITTED: 'info',
        APPROVED: 'success',
        REJECTED: 'error'
      };
      const option = submitStatusOptions.find(o => o.value === row.submitStatus);
      return <NTag type={tagTypes[row.submitStatus] || 'default'}>{option?.label || row.submitStatus}</NTag>;
    }
  },
  { key: 'submitByName', title: $t('page.dataplatform.fill.submitBy'), width: 120 },
  { key: 'submitTime', title: $t('page.dataplatform.fill.submitTime'), width: 180 },
  { key: 'approveByName', title: $t('page.dataplatform.fill.approveBy'), width: 120 },
  { key: 'approveTime', title: $t('page.dataplatform.fill.approveTime'), width: 180 },
  { key: 'createTime', title: $t('page.dataplatform.common.createTime'), width: 180 },
  {
    key: 'actions',
    title: $t('page.dataplatform.common.action'),
    width: 320,
    fixed: 'right' as const,
    render: (row: Api.Dataplatform.FillData) => {
      return (
        <NSpace>
          {row.submitStatus === 'DRAFT' && (
            <>
              <NButton size="small" type="primary" onClick={() => handleEdit(row)}>
                {$t('common.edit')}
              </NButton>
              <NPopconfirm onPositiveClick={() => handleSubmit(row.id)}>
                {{
                  default: () => $t('page.dataplatform.fill.confirmSubmit'),
                  trigger: () => (
                    <NButton size="small" type="info">
                      {$t('page.dataplatform.fill.submit')}
                    </NButton>
                  )
                }}
              </NPopconfirm>
            </>
          )}
          {row.submitStatus === 'SUBMITTED' && (
            <NButton size="small" type="warning" onClick={() => handleApprove(row)}>
              {$t('page.dataplatform.fill.approve')}
            </NButton>
          )}
          <NButton size="small" onClick={() => handleView(row)}>
            {$t('common.view')}
          </NButton>
          {row.submitStatus === 'DRAFT' && (
            <NPopconfirm onPositiveClick={() => handleDelete(row.id)}>
              {{
                default: () => $t('common.confirmDelete'),
                trigger: () => (
                  <NButton size="small" type="error">
                    {$t('common.delete')}
                  </NButton>
                )
              }}
            </NPopconfirm>
          )}
        </NSpace>
      );
    }
  }
];

async function getTableData() {
  startLoading();
  const { data, error } = await fetchFillDataList(queryParams);
  if (!error) {
    tableData.value = data?.rows || [];
    total.value = data?.total || 0;
  }
  endLoading();
}

function handleQuery() {
  queryParams.pageNum = 1;
  getTableData();
}

function handleReset() {
  Object.assign(queryParams, {
    pageNum: 1,
    pageSize: 10,
    templateId: undefined,
    submitStatus: undefined,
    approvalStatus: undefined,
    submitBy: undefined,
    projectId: undefined
  });
  getTableData();
}

function handleAdd() {
  operateType.value = 'add';
  editingData.value = null;
  openDrawer();
}

function handleEdit(row: Api.Dataplatform.FillData) {
  operateType.value = 'edit';
  editingData.value = row;
  openDrawer();
}

function handleView(row: Api.Dataplatform.FillData) {
  operateType.value = 'edit';
  editingData.value = row;
  openDrawer();
}

function handleApprove(row: Api.Dataplatform.FillData) {
  approvingData.value = row;
  openApproval();
}

async function handleSubmit(id: number) {
  const { error } = await submitFillData(id);
  if (!error) {
    window.$message?.success($t('page.dataplatform.fill.submitSuccess'));
    getTableData();
  }
}

async function handleDelete(id: number) {
  const { error } = await deleteFillData([id]);
  if (!error) {
    window.$message?.success($t('common.deleteSuccess'));
    getTableData();
  }
}

function handlePageChange(page: number) {
  queryParams.pageNum = page;
  getTableData();
}

function handlePageSizeChange(pageSize: number) {
  queryParams.pageSize = pageSize;
  queryParams.pageNum = 1;
  getTableData();
}

function handleOperateSuccess() {
  closeDrawer();
  getTableData();
}

function handleApprovalSuccess() {
  closeApproval();
  getTableData();
}

// 初始化
getTableData();
</script>

<template>
  <div class="h-full flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <NCard :title="$t('page.dataplatform.fill.dataManagement')" :bordered="false" size="small" class="sm:flex-1-hidden card-wrapper">
      <template #header-extra>
        <NButton type="primary" size="small" @click="handleAdd">
          <icon-ic-round-plus class="mr-4px text-20px" />
          {{ $t('common.add') }}
        </NButton>
      </template>

      <div class="h-full flex-col">
        <NSpace class="pb-12px" justify="space-between">
          <NSpace>
            <NSelect
              v-model:value="queryParams.submitStatus"
              :placeholder="$t('page.dataplatform.fill.submitStatus')"
              :options="submitStatusOptions"
              clearable
              class="w-150px"
            />
          </NSpace>
          <NSpace>
            <NButton @click="handleReset">{{ $t('common.reset') }}</NButton>
            <NButton type="primary" @click="handleQuery">{{ $t('common.search') }}</NButton>
          </NSpace>
        </NSpace>

        <NDataTable
          :columns="columns"
          :data="tableData"
          :loading="loading"
          :scroll-x="1600"
          :pagination="{
            page: queryParams.pageNum,
            pageSize: queryParams.pageSize,
            itemCount: total,
            showSizePicker: true,
            pageSizes: [10, 20, 50, 100],
            onUpdatePage: handlePageChange,
            onUpdatePageSize: handlePageSizeChange
          }"
          class="flex-1-hidden"
        />
      </div>
    </NCard>

    <DataOperateDrawer
      v-model:visible="visible"
      :operate-type="operateType"
      :row-data="editingData"
      @success="handleOperateSuccess"
    />

    <DataApprovalModal
      v-model:visible="approvalVisible"
      :data="approvingData"
      @success="handleApprovalSuccess"
    />
  </div>
</template>

<style scoped></style>
